package com.example.user.customviewdemo.index;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.example.user.customviewdemo.R;

import java.util.ArrayList;

public class IndexSideBarActivity extends AppCompatActivity {

    private IndexSideBar indexSideBar;
    private TextView textView;
    private ListView mListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index_side_bar);

        indexSideBar = (IndexSideBar) findViewById(R.id.indexsidebar);
        textView = (TextView) findViewById(R.id.textview);
        mListView = (ListView) findViewById(R.id.listview);

        final ArrayList<String> data = getData();
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,data);
        mListView.setAdapter(adapter);

        indexSideBar.setIndicatorView(textView);
        indexSideBar.setOnChooseListener(new IndexSideBar.OnChooseListener() {
            @Override
            public void onChoose(int index, String str) {
                int position = new MySectionIndexer(data,IndexSideBar.str).getPositionForSection(index);
                mListView.setSelection(position);
            }
        });


    }

    /**
     *  获取数据源
     * @return
     */
    private ArrayList<String> getData(){
        ArrayList<String> data = new ArrayList<>();
        String str = IndexSideBar.str;
        for (int i = 0;i<str.length();i++){
            String s = String.valueOf(str.charAt(i));
            for (int j = 0;j<10;j++){
                data.add(s + j);
            }
        }
        return data;
    }


    /**
     * 根据索引字符数组和数据源获取listview中索引字符首次出现的item  position
     * 之所以实现SectionIndexer，只是一个标准，我们完全可以不实现这个接口而只写getPositionForSection(int sectionIndex)这个方法
     */
    private static class MySectionIndexer implements SectionIndexer{
        private ArrayList<String> data;
        private String str;
        public MySectionIndexer(ArrayList<String> data,String str){
            this.data = data;
            this.str = str;
        }

        @Override
        public Object[] getSections() {//正常情况应该返回索引条中的字符索引
            return null;
        }

        /**
         * 这个才是我们实现的重点方法，其他的都可以不实现，该方法一般使用二分法查找法
         * @param sectionIndex  字符索引所在索引条中的index
         * @return  该字符索引在listview中首次出现position
         */
        @Override
        public int getPositionForSection(int sectionIndex) {
            return sectionIndex*10;
        }

        @Override
        public int getSectionForPosition(int position) {
            return 0;
        }
    }


}
